package com.cy.pj.modules.job;

import com.cy.pj.modules.entity.Sku;
import com.cy.pj.modules.entity.Spu;
import com.cy.pj.modules.mapper.SkuMapper;
import com.cy.pj.modules.mapper.SpuMapper;
import com.cy.pj.modules.service.ISpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 库存汇总定时任务, 暂定1小时 后期每晚12.00
 * @author Kiven
 */
@Component
public class SkuSpuStockJobHandler {

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private ISpuService spuService;

    // sku库存汇总  延时一小时在启动,initialDelay=60*60*1000
   @Scheduled(fixedDelay=60*60*1000,initialDelay=60*60*1000)
    public void stockHandler(){
        List<Spu> spus = spuMapper.selectSpuListAll();
        for (Spu spu : spus) {
            Sku sku = new Sku();
            sku.setSpuId(spu.getId());
            List<Sku> skus = skuMapper.selectSkuList(sku);
            long sum = skus.stream().mapToLong(Sku::getNumber).sum();
            spu.setNum(sum);
            spuService.updateSpu(spu);
        }
    }

}
